package com.hq.zb.controller;


import com.hq.zb.dto.Attachment;
import com.hq.zb.service.IAttachmentService;
import com.hq.zb.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-27
 */
@RestController
@RequestMapping("/sys")
public class AttachmentController {

    @Autowired
    private IAttachmentService attachmentService;

    /**
     * 上传附件
     * @param file
     * @param attachment
     * @return
     */
    @PostMapping("/attachment/upload")
    public Result upload(@RequestParam("image") MultipartFile file, @RequestBody Attachment attachment){
        //原始文件名称比如 aa.png
        String originalFilename = file.getOriginalFilename() ;
        //将原始名称修改为：唯一文件名称
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传文件，上传到哪呢？图片服务器七牛云
        //把图片发放到距离图片最近的服务器上，降低我们自身服务器的带宽消耗
        String url = attachmentService.upload(file, fileName, attachment);
        if (StringUtils.isNotEmpty(url)){
            //上传成功
            return Result.ok(url) ;
        }
        return Result.error(20001,"图片 上传失败！") ;
    }

    /**
     * 删除附件
     * @param attachment
     * @return
     */
    @PostMapping("/attachment/delete")
    public Result deleteAttachment(@RequestBody Attachment attachment){
        attachmentService.deleteAttachment(attachment);
        return Result.ok() ;
    }
}

